package com.zzz.gp.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @description:
 * @author: ZZZ
 * @time: 2023/8/31 18:08
 */
@RestController
public class FileController {
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));

        // 上传后的路径
        String filePath = "D:/file/";

        // 解决中文问题，liunx下中文路径，图片显示问题
        //fileName = UUID.randomUUID() + suffixName;

        // 构建上传路径
        File dest = new File(filePath + fileName);

        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        try {
            // 保存文件
            file.transferTo(dest);
            return "上传成功";
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

    @GetMapping("/download")
    public void downloadFile(HttpServletResponse response) {
        try {
            //获取要下载的文件
            File file = new File("D:/file/zzz.docx");

            //设置响应的内容类型为二进制流，即文件类型
            response.setContentType("application/octet-stream");

            //设置文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));

            //创建输入流
            FileInputStream inputStream = new FileInputStream(file);
            BufferedInputStream buffInputStream = new BufferedInputStream(inputStream);

            //创建输出流
            ServletOutputStream outputStream = response.getOutputStream();
            BufferedOutputStream buffOutputStream = new BufferedOutputStream(outputStream);

            //循环读取数据并写入到响应输出流中
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = buffInputStream.read(buffer)) != -1) {
                buffOutputStream.write(buffer, 0, len);
            }

            //关闭流
            buffOutputStream.flush();
            buffOutputStream.close();
            outputStream.flush();
            outputStream.close();
            buffInputStream.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
